//#include "stdafx.h"
#include "protocol_head.h"
#include "base_time.h"



/**
*	ַַ󴮱Ƚ
*/
bool CharCompareToHex (unsigned char* pInData, unsigned int nInLen,
							  unsigned char* pOutHexStr /*nInLen*2 + 1*/)
{
	unsigned char * c = (unsigned char *)pInData;
	for (unsigned int i=0; i<nInLen; i++)
	{
		unsigned char ch = *c++;
		unsigned char lo = ch & 0xF;
		unsigned char hi = ch >> 4;
		unsigned char c_hi = *pOutHexStr ++;
		unsigned char c_lo = *pOutHexStr ++;
		if (hi > 9)
		{
			hi -= 10;
			if (c_hi != ('A' + hi) && c_hi != ('a' + hi))
				return false;
		}
		else
		{
			if (c_hi != ('0' + hi))
				return false;
		}

		if (lo > 9)
		{
			lo -= 10;
			if (c_lo != ('A' + lo) && c_lo != ('a' + lo))
				return false;
		}
		else
		{
			if (c_lo != ('0' + lo))
				return false;
		}

	}

	return true;
}

/**
* ϽַתΪַ?
*/
void CharToHex (unsigned char* pInData, unsigned int nInLen,
							   unsigned char* pOutHexStr /*nInLen*2 + 1*/)
{
	unsigned char * c = (unsigned char *)pInData;
	for (unsigned int i=0; i<nInLen; i++)
	{
		unsigned char ch = *c++;
		unsigned char lo = ch & 0xF;
		unsigned char hi = ch >> 4;
		*pOutHexStr ++ = hi > 9 ? ('A' + hi - 10) : ('0' + hi);
		*pOutHexStr ++ = lo > 9 ? ('A' + lo - 10) : ('0' + lo);
	}
} 

bool _DATA_HEAD::CheckMD5()
{
	MD5_CTX md5_ctx;
	md5_init(&md5_ctx);

	unsigned char strTmpMD5[16];
	char strTmp[22];
	memcpy(strTmp, strVersion, sizeof(strVersion));
	memcpy(strTmp + sizeof(strVersion), strTime, sizeof(strTime));

	md5_update(&md5_ctx, (unsigned char *)strTmp, sizeof(strTmp));

	md5_final(&md5_ctx, strTmpMD5);

	return CharCompareToHex(strTmpMD5, 16, strMd5);
}

void _DATA_HEAD::CreateMD5()
{
	MD5_CTX md5_ctx;
	md5_init(&md5_ctx);

	char strTmp[22];
	unsigned char strTmpMd5[16];
	memcpy(strTmp, strVersion, sizeof(strVersion));
	memcpy(strTmp + sizeof(strVersion), strTime, sizeof(strTime));

	md5_update(&md5_ctx, (unsigned char *)strTmp, sizeof(strTmp));

	md5_final(&md5_ctx, strTmpMd5);

	CharToHex(strTmpMd5, sizeof(strTmpMd5), strMd5);
}

void _DATA_HEAD::Init(char* pVersion)
{
	strncpy(strVersion, pVersion, sizeof(strVersion));

	HT::Time tt(time(NULL));
	sprintf(strTime, "%06d%02d%02d%02d%02d%02d",
		tt.GetYear(), tt.GetMonth(), tt.GetDay(), tt.GetHour(), tt.GetMinute(), tt.GetSecond());

	CreateMD5();
}
